import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from "mobx"
import { WeaAlertPage, WeaLocaleProvider, WeaRightMenu, WeaNewScroll, WeaReqTop, WeaAuth, WeaProgress, WeaInput } from 'ecCom';
import { Button, message } from 'antd';
const getLabel = WeaLocaleProvider.getLabel;
import Comment from '../dialog/index';
import GovernMind from '../governMind/index';
import GovernReport from '../governReport/index';
import GovernInstruct from '../governInstruct/index';
import GovernLogList from '../governLog/index';
import GovernShare from '../governShare/index';
import GovernAnalysis from '../governAnalysis/index';
import Model from '../model/index';
import BtnType from "../../../util/btnType";
import CubeLayout from "../cubeLayout";
import GovernTag from '../governPoint/tag';
import { routerShape } from 'react-router';
import { Common } from '../governText/text';
const common = new Common();

@inject("proinfoStore")
@observer
export default class Proinfo extends React.Component {
    static contextTypes = {
        router: routerShape
    }
    constructor(props) {
        super(props);
        this.state = {}
    }
    componentDidMount() {
        const { proinfoStore } = this.props;
        const { id, type, selectTabKey,none } = this.props.location.query;
        proinfoStore.getTitle({ "id": id, "type": type, "selectTabKey": selectTabKey,"none":none });
    }
    componentWillReceiveProps(nextProps) {

    }
    render() {
        const { proinfoStore, location: { pathname, search } } = this.props;
        const { MenuCurFlag, skey, id } = proinfoStore;
        let taskId = MenuCurFlag ? skey : id;
        const { status, modelType, shareStore, loaded, isRight } = proinfoStore;
        const { showAdd, shareCondition } = shareStore;
        const { loading, selectTabKey, maininfoTitle, sKeyFlag, isdelete } = status;
        let rightMenu = this.getRightMenu();
        if (loaded && !isRight) {
            return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@7cuiq7`} >
                <div style={{ color: '#000' }}>
                    {getLabel(2012, "对不起，您暂时没有权限！")}
                </div>
            </WeaAlertPage>
            )
        }
        let style = isdelete == 1 ? { color: '#D1D1D1' } : {};
        return (
            <div className="g-proinfo" style={{ padding: '0px' }}>
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@mu1bj7`} style={{ color: "#ccc" }} datas={rightMenu} onClick={this.onRightMenuClick}>
                    <WeaReqTop ecId={`${this && this.props && this.props.ecId || ''}_WeaReqTop@eb1qgs`}
                        title={<span style={style}>{maininfoTitle}{sKeyFlag == 1 ?<span className="g-top-cui">{common.URGE}</span> : null}</span>}
                        loading={loading}
                        icon={<i className='icon-coms-government' />}
                        iconBgcolor='#f14a2d'
                        tabDatas={this.gettabDatas()}
                        selectedKey={selectTabKey}
                        buttons={this.getQuickBtn()}
                        onChange={this.taskCardChangeTab}
                        showDropIcon={true}
                        dropMenuDatas={rightMenu}
                        onDropMenuClick={this.onRightMenuClick}
                    >
                        <div className="g-proinfo">
                            <div className='g-proinfo-content-inner'>
                                <div style={{ height: '100%' }}>
                                    {this.getTabs()}
                                </div>
                                <Model ecId={`${this && this.props && this.props.ecId || ''}_Model@gmoffu`} modelType={modelType} id={taskId} contentStore={proinfoStore} pathname={pathname} search={search}></Model>
                                <WeaAuth ecId={`${this && this.props && this.props.ecId || ''}_WeaAuth@ugo1nr`}
                                    visible={showAdd}
                                    conditions={shareCondition}
                                    title={getLabel('18645', '添加共享')}
                                    onOk={this.addShare}
                                    onCancel={this.onCancel}
                                    icon="icon-coms-government"
                                    iconBgcolor="#f14a2d"
                                />
                            </div>
                        </div>
                    </WeaReqTop>
                </WeaRightMenu>
            </div>
        )
    }

    addShare = (v) => {
        const { proinfoStore } = this.props;
        const { MenuCurFlag, skey, id } = proinfoStore;
        let taskId = MenuCurFlag ? skey : id;
        const { shareStore } = proinfoStore;
        shareStore.addShare({ "id": taskId, ...v });
    }

    onCancel = () => {
        const { proinfoStore } = this.props;
        const { shareStore } = proinfoStore;
        shareStore.onShowAdd(false)
    }
    /**
     * 解析栏目
     */
    gettabDatas = () => {
        const { proinfoStore } = this.props;
        const { status } = proinfoStore;
        const { columns,orderList} = status;
        let tabDatas = [];
        orderList.map((o)=>{
            let column = columns[o];
            tabDatas.push(column);
        })
        return tabDatas;
    }

    /**
     * 快捷按钮及右键按钮方法
     */
    onRightMenuClick = (key) => {
        if (key == BtnType.BTN_DELETE || key == BtnType.BTN_EDIT) {
            const { proinfoStore } = this.props;
            const { giStore } = proinfoStore;
            const { tableStoreMyAttent } = giStore;
            let selectedRowKeys = tableStoreMyAttent.selectedRowKeys;
            if (selectedRowKeys == '') {
                message.error(key == BtnType.BTN_DELETE ? `${getLabel(386176, '请选择需要删除的记录！')}` : `${getLabel(500698, '请选择需要编辑的记录！')}`);
                return;
            }
            if (key == BtnType.BTN_EDIT && selectedRowKeys.length > 1) {
                message.error(`${getLabel(31014, '只能操作一条记录，请重新选择')}`);
                return;
            }
        } else if (key == BtnType.BTN_DELETEBATCH) {
            const { proinfoStore } = this.props;
            const { shareStore } = proinfoStore;
            const { tableStoreMyAttent } = shareStore;
            let selectedRowKeys = tableStoreMyAttent.selectedRowKeys;
            if (selectedRowKeys == '') {
                message.error(`${getLabel(386176, '请选择需要删除的记录！')}`);
                return;
            }
        }
        this.props.proinfoStore.doAction(key);
        //lusx 详情页面，弹框保存后页面不刷新 19.1.30
        const { pathname, search } = this.props;
        let url = `/${pathname}${search}`;
        if (pathname == undefined || search == undefined) {
            let taskid = this.props.proinfoStore.id;
            url = "/main/govern/proinfo?id=" + taskid;
        }
        this.context.router.push({
            pathname: url
        });
        let tabKey = parseInt(key) ;
        if(tabKey<=0){
            const { proinfoStore } = this.props;
            const { status} = proinfoStore;
            const { columns } = status;
            let columns0 = toJS(columns);
            let mathKey = Math.abs(key).toString();
            if (columns0[mathKey]) {
                this.taskCardChangeTab(mathKey);
            } else{
                const { rightMenu = {} } = status;
                const rs = toJS(rightMenu["0"]) || [];
                rs.map((i) => {
                    let tabKey_1 = Math.abs(i.key).toString();
                    let openUrl = "";
                    if(mathKey == tabKey_1){
                        if(i.type =="0"){
                            openUrl = "/spa/govern/static/index.html#/main/govern/proinfo?id="+this.props.proinfoStore.id+"&selectTabKey="+mathKey+"&none=1" ;
                        }else if (i.type =="1"){
                            openUrl = i.linkurl || "" ;
                        }
                        if(openUrl !=""){
                            window.open(openUrl);
                        }
                    }
                });
            }
        }

    }

    /**
     * 解析右键按钮
     */
    getRightMenu = () => {
        const { proinfoStore } = this.props;
        const { status, rightMenuCur = [] } = proinfoStore;
        const { selectTabKey, rightMenu = {} } = status;
        const rs = rightMenuCur.length > 0 ? rightMenuCur : (toJS(rightMenu[selectTabKey]) || []);
        let rms = []
        rs.map((i) => {
            rms.push({
                key: i.key,
                icon: <i className={i.icon} />,
                content: i.label
            })
        });
        return rms;
    }

    /**
     * 解析快捷按钮(右侧操作按钮)
     */
    getQuickBtn = () => {
        const { proinfoStore } = this.props;
        const { status } = proinfoStore;
        const { selectTabKey, rightMenu = {} } = status;
        const rs = toJS(rightMenu[selectTabKey]) || [];
        let rms = []
        rs.map((i) => {
            let tabKey = parseInt(i.key) ;
            if(tabKey>0){
                rms.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fv2aiw@${i.key}`} type="primary" onClick={() => this.onRightMenuClick(i.key)}>{i.label}</Button>)
            }
        });
        return rms;
    }

    /**
     * 解析卡片主体区域
     */
    getTabs = () => {
        const { proinfoStore, location } = this.props;
        const { status, id, type, grStore, logStore, gpStore, shareStore, governMindStore, governAnalysisStore, docStore, giStore, geStore, gcStore, cubeLayoutParame, getCardStorefun } = proinfoStore;
        const { selectTabKey, columns } = status;
        let labelTime = '';
        let labelPers = '';
        let labelTask = '';
        if (selectTabKey === "0") {//督办详情
            //return <Comment id={id} type={type}></Comment>;
            return (
                Object.keys(cubeLayoutParame).length > 0 ? (CubeLayout({ cubeLayoutParame, getCardStorefun, "getEcmeFieldData": this.getEcmeFieldData, })) : <Comment ecId={`${this && this.props && this.props.ecId || ''}_Comment@lge8tz`} id={id} type={type}></Comment>
            )
        } else if (selectTabKey === "1") {//思维导图
            return <GovernMind ecId={`${this && this.props && this.props.ecId || ''}_GovernMind@mjfgds`} id={id} proinfoStore={proinfoStore} governMindStore={governMindStore} governAnalysisStore={governAnalysisStore}></GovernMind>;
        } else if (selectTabKey === "2") {//汇报列表
            labelTime = getLabel('21950,19736', "反馈时间");
            labelPers = getLabel('21950,127', "反馈人");
            labelTask = getLabel('1352', '任务名称');
            return <GovernReport ecId={`${this && this.props && this.props.ecId || ''}_GovernReport@atlame`} key="report" id={id} governReportStore={grStore} type={0} labelTime={labelTime} labelPers={labelPers} labelTask={labelTask} location={location}></GovernReport>
        } else if (selectTabKey === "3") {//日志列表
            return <GovernLogList ecId={`${this && this.props && this.props.ecId || ''}_GovernLogList@5i402r`} id={id} governReportStore={logStore}></GovernLogList>
        } else if (selectTabKey === "4") {//催办列表
            labelTime = getLabel('23756,19736', "催办时间");
            labelPers = getLabel('23756,127', "催办人");
            return <GovernReport ecId={`${this && this.props && this.props.ecId || ''}_GovernReport@91z70g`} key="prompt" id={id} governReportStore={gpStore} type={1} labelTime={labelTime} labelPers={labelPers} location={location}></GovernReport>
        } else if (selectTabKey === "5") {//共享信息
            return <GovernShare ecId={`${this && this.props && this.props.ecId || ''}_GovernShare@wti2km`} id={id} governShareStore={shareStore}></GovernShare>
        } else if (selectTabKey === "6") {//统计信息
            return <GovernAnalysis ecId={`${this && this.props && this.props.ecId || ''}_GovernAnalysis@jphyx1`} id={id} governAnalysisStore={governAnalysisStore}></GovernAnalysis>
        } else if (selectTabKey === "7") {//成文信息
            labelTime = getLabel('388369,19736', "成文时间");
            labelPers = getLabel('388369,127', "成文人");
            return <GovernReport ecId={`${this && this.props && this.props.ecId || ''}_GovernReport@zh75zq`} key="doc" id={id} governReportStore={docStore} type={2} labelTime={labelTime} labelPers={labelPers} location={location}></GovernReport>
        } else if (selectTabKey === "2.1") {//主办单位反馈
            labelTime = getLabel('21950,19736', "反馈时间");
            labelPers = getLabel('21950,127', "反馈人");
            labelTask = getLabel('1352', '任务名称');
            return <GovernReport ecId={`${this && this.props && this.props.ecId || ''}_GovernReport@jyisnm`} reportType="1" key="report" id={id} governReportStore={grStore} type={0} labelTime={labelTime} labelPers={labelPers} labelTask={labelTask} location={location}></GovernReport>
        } else if (selectTabKey === "2.2") {//协办单位反馈
            labelTime = getLabel('21950,19736', "反馈时间");
            labelPers = getLabel('21950,127', "反馈人");
            labelTask = getLabel('1352', '任务名称');
            return <GovernReport ecId={`${this && this.props && this.props.ecId || ''}_GovernReport@73dmkc`} reportType="2" key="report" id={id} governReportStore={grStore} type={0} labelTime={labelTime} labelPers={labelPers} labelTask={labelTask} location={location}></GovernReport>
        } else if (selectTabKey === "8") {//领导点评
            labelTime = getLabel('33706,386763', "批示时间");
            labelPers = getLabel('33706,31807', "批示领导");
            return <GovernInstruct ecId={`${this && this.props && this.props.ecId || ''}_GovernInstruct@7za28b`} id={id} key="ins" governReportStore={giStore} type={5} labelTime={labelTime} labelPers={labelPers} location={location}></GovernInstruct>
        } else if (selectTabKey === "17") {//延期信息
            labelTime = getLabel('855', "申请日期");
            labelPers = getLabel('368', "申请人");
            return <GovernReport ecId={`${this && this.props && this.props.ecId || ''}_GovernReport@rcd8iq`} id={id} key="extension" governReportStore={geStore} type={3} labelTime={labelTime} labelPers={labelPers} location={location}></GovernReport>
        } else if (selectTabKey === "18") {//办结信息
            labelTime = getLabel('82308', "办结日期");
            labelPers = getLabel('368', "申请人");
            return <GovernReport ecId={`${this && this.props && this.props.ecId || ''}_GovernReport@q3z149`} id={id} key="cutoff" governReportStore={gcStore} type={4} labelTime={labelTime} labelPers={labelPers} location={location}></GovernReport>
        } else {
            let linkurl = "";
            let columns0 = toJS(columns);
            if (columns0[selectTabKey]) {
                linkurl = columns0[selectTabKey].linkurl || "";
                return <iframe src={linkurl} id="prjtabiframe" name="prjtabiframe" className="flowFrame" frameborder="0" width="100%" height="100%" />
            } else {
                if (selectTabKey) {
                    this.taskCardChangeTab("0");
                }
                return <div />
            }
        }
    }

    /**
     * 切换栏目
     */
    taskCardChangeTab = (key) => {
        const { proinfoStore } = this.props;
        proinfoStore.changeTab(key);
    }

    //重定义进度dom
    progressItem(field) {
        const { proinfoStore } = this.props;
        let percent = 0;
        let isFinishTask = false;
        if (proinfoStore.modelStore.isFinishTask) {
            isFinishTask = proinfoStore.modelStore.isFinishTask;
        }

        if (field.value != "") {
            // percent = Number(field.value);
            percent = field.value;
        } else if (isFinishTask == true) {
            percent = 100;
        } else {
            percent = 0;
        }
        return <div><WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@rajjm4`} percent={percent} strokeColor="#28ce87" /></div>
    }

    //重定义状态dom
    statusItem(field) {
        const { proinfoStore } = this.props;
        let isFinishTask = false;
        let isDiscard = false;
        if (proinfoStore.modelStore.isFinishTask || proinfoStore.modelStore.isDiscard) {
            isFinishTask = proinfoStore.modelStore.isFinishTask;
            isDiscard = proinfoStore.modelStore.isDiscard;
        }
        return <div><GovernTag ecId={`${this && this.props && this.props.ecId || ''}_GovernTag@xti3ov`} record={field} isFinishTask={isFinishTask} isDiscard={isDiscard} /></div>
    }

    getInput(field) {
        return <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@c6zb40`} viewAttr={1} value={field.value} />
    }

    //解析字段时回调  传入字段的id（field-111）等及相关信息
    getEcmeFieldData = (path, param) => {
        const { cubeLayoutParame } = this.props.proinfoStore;
        const { specialFields } = cubeLayoutParame

        if (_.has(specialFields, path)) {
            if (specialFields[path].fieldname == 'progress') {
                return this.progressItem(param);
            }
            if (specialFields[path].fieldname == 'status') {
                return this.statusItem(param);
            }
            return this.getInput(param);
        }
        return null;
    }
}